<template>
    <el-dialog title="修改密码" :visible="pwdEdit" @close="close">
        <el-form ref="form" label-width="100px" :rules="rules" :model="form">
            <el-form-item label="新密码" prop="newpwd">
                <el-input v-model="form.newpwd" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmpwd">
                <el-input v-model="form.confirmpwd" placeholder="请再次输入新密码"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="onSubmit('form')">保存</el-button>
            <el-button plain @click="close">取消</el-button>
        </span>
    </el-dialog>
</template>

<script>
  import { userUpdate } from '@/api/user'

  export default {
    name: 'EditPassword',
    props: ['employeeId', 'pwdEdit'],
    data() {
      return {
        defaultForm: {
          newpwd: '',
          confirmpwd: ''
        },
        form: {
          newpwd: '',
          confirmpwd: ''
        },
        rules: {
          newpwd: [
            { required: true, message: '请再次输入新密码', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          confirmpwd: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ]
        }
      }
    },
    created: function() {
      this.form = this.defaultForm
    },
    watch: {
      pwdEdit(val) {
        if (val) {
          this.initForm()
        }
      }
    },
    methods: {
      initForm() {
        this.$nextTick(() => {
          this.$refs['form'] && this.$refs['form'].clearValidate()
        })
      },
      close() {
        this.$emit('update:pwdEdit', false)
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.form.newpwd !== this.form.confirmpwd) {
              this.$message({ message: '两次输入密码不一致', type: 'error', showClose: true })
              return
            }
            userUpdate({ id: this.employeeId, pwd: this.form.newpwd }).then(response => {
              if (response) {
                this.$message({ message: '修改密码成功', type: 'success', showClose: true })
                this.$emit('update:pwdEdit', false)
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
